package com.shop.dao.impl;

import com.shop.dao.GoodsDao;
import com.shop.entity.Goods;
import com.shop.entity.ShowPageT;
import com.shop.tools.JdbcTool;

import java.sql.SQLException;
import java.util.List;

/**
 * com.shop.dao.impl文档说明
 *
 * @author Angluzha
 * @version 2022/9/15
 */
public class GoodsDaoImpl implements GoodsDao<Goods> {
    @Override
    public Goods selectOne(Goods goods) throws SQLException {
        String sql = "select * from goods where statu = 1 and id = ? or gname = ?";
        return JdbcTool.selectOne(Goods.class,sql,goods.getId(),goods.getGname());
    }

    @Override
    public boolean update(Goods g) {
        String sql = "update goods set gname=?,des=?,price=?,type1=?,type2=?,statu=?,stock=?,pnguri=? where id =?";
        return JdbcTool.write(sql,g.getGname(),g.getDes(),g.getPrice(),g.getType1(),g.getType2(),g.getStatu(),g.getStock(),g.getPnguri(),g.getId())>0;
    }

    @Override
    public boolean insert(Goods g) {
        String sql = "insert into goods(gname,des,price,type1,type2,statu,stock,pnguri) values(?,?,?,?,?,?,?,?)";
        return JdbcTool.write(sql,g.getGname(),g.getDes(),g.getPrice(),g.getType1(),g.getType2(),g.getStatu(),g.getStock(),g.getPnguri())>0;
    }

    @Override
    public boolean deleteById(Integer id) {
        String sql = "update goods set statu=2 where id = ?";
        return JdbcTool.write(sql,id)>0;
    }

    @Override
    public List<Goods> selectAll() throws SQLException {
        String sql = "select * from goods where statu = 1";
        return JdbcTool.selectList(Goods.class,sql);
    }

    @Override
    public ShowPageT<Goods> selectPage(ShowPageT<Goods> page) throws SQLException {
        String sql = "SELECT * FROM goods where statu = 1 LIMIT ?,?";
        String sql2 = "select count(1) from goods";
        page.setCount(JdbcTool.selectResult(Integer.class,sql2));
        page.setData(JdbcTool.selectList(Goods.class,sql,page.getSize()*(page.getPage()-1),page.getSize()));
        return page;
    }

    @Override
    public int delCheck(List<Integer> list) {
        StringBuffer sql = new StringBuffer("update goods set statu=2  where id in(");
        list.forEach(e->{
            sql.append("?,");
        });
        sql.deleteCharAt(sql.length()-1).append(")");
        return JdbcTool.write(String.valueOf(sql),list.toArray());
    }

    @Override
    public void payFor(Integer goods, Integer quantity) {
        String sql = "update goods set stock =stock-? where id=?";
        JdbcTool.write(sql,quantity,goods);
    }
}
